<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
    <div class="box"><el-button type="success" round class="btn" @click="$router.push('/employees')">退出</el-button></div>
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { addEmployeeBatch } from '@/api/employees'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '请上传小于1m的文件!',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // 将excel读取出来的数据进行格式化处理
      const data = this.transToExcel(results)
      // 发送ajax请求批量添加数据(格式之后的数据)
      this.doAdd(data)
    },
    // 批量导入
    async doAdd(data) {
      try {
        const res = await addEmployeeBatch(data)
        console.log('addEmployeeBatch', res)
        // 保存数据
      } catch (err) {
        console.log('addEmployeeBatch', err)
      }
    },
    // 中文转英文
    transToExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'

      }
      const result = data.map(zhObj => {
        const zhKey = Object.keys(zhObj)
        const enKesys = {}
        // console.log(zhKey)
        zhKey.forEach(zhKeys => {
          const enKey = mapInfo[zhKeys]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enKesys[enKey] = formatExcelDate(zhObj[zhKeys])
          } else {
            enKesys[enKey] = zhObj[zhKeys]
          }
        })
        return enKesys
      })
      return result
    }
  }
}
</script>
<style>
    .box{
        width: 300px;
        margin: 20px auto;
    }
    .btn{
        width: 300px;
    }
</style>
